/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.me.androidresttest;

import android.app.Activity;
import android.app.Application;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author Peter
 */
public class MainActivity extends Activity {

    Button loadButton = null;
    Button tloadButton = null;
    Button endButton = null;
    EditText urlText = null;
    EditText resultText = null;
    String buffer = "";
    public static final String MY_IPADDRESS = "128.237.252.164";
    private static final String NAMESPACE = "http://service.stepapp.me.org/";
    private static final String URL = "http://" + MY_IPADDRESS + ":8080/StepAppServer/StepAppService";
//    private static String SOAP_ACTION; // = "http://calc.me.org/add";
    private static String METHOD_NAME; // = "add";
    WSCaller caller = null;
    private String service_url;

    public String getService_url() {
        return service_url;
    }

    public void setService_url(String service_url) {
        this.service_url = service_url;
    }

    private void initCaller() {
        if (this.caller == null) {
            this.caller = new WSCaller(NAMESPACE, URL);
        }
    }

    private String test() {
        String result = "No luck";
        initCaller();

        TelephonyManager tMgr = (TelephonyManager) this.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String mPhoneNumber = tMgr.getLine1Number();
        

        boolean hope = caller.newUser(mPhoneNumber, "myConputerEmulator");

        if (hope) {
            result = "Yeah!";
        }
        return result;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        endButton = (Button) findViewById(R.id.Button_quit);
        loadButton = (Button) findViewById(R.id.Button_load);
        tloadButton = (Button) findViewById(R.id.Button_threadload);
        urlText = (EditText) findViewById(R.id.url);
        resultText = (EditText) findViewById(R.id.Result);

        this.setURLAddress("http://" + MY_IPADDRESS + ":8080/StepAppServer/resources/stepappUsers/");

        loadButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                setText(MainActivity.this.test());

//                setText(MainActivity.this.DownloadText(getURLAddress()));
            }
        });

        tloadButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Context context = MainActivity.this.getApplicationContext();
                CharSequence text = "tloadButton";
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                Thread t = new Thread() {

                    public void run() {
                        Message lmsg;
                        lmsg = new Message();
                        lmsg.obj = "hello";
                        lmsg.what = 1;

                        mHandler.sendMessage(lmsg);

                        String mybuf = MainActivity.this.DownloadText(getURLAddress());

                        lmsg = new Message();
                        lmsg.obj = mybuf;
                        lmsg.what = 0;
                        mHandler.sendMessage(lmsg);
                    }
                };
                t.start();
            }
        });

        endButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                finish();
            }
        });

        this.mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {


                Context context = MainActivity.this.getApplicationContext();
                CharSequence text = "message:" + msg.what + " " + ((String) msg.obj);
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                switch (msg.what) {
                    case 0:
                        // process incoming messages here
                        setText((String) msg.obj);
                        break;
                    default:
                }
            }
        };
    }
    private Handler mHandler;

    private String DownloadText(String URL) {
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }

        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];
        try {
            while ((charRead = isr.read(inputBuffer)) > 0) {
                //---convert the chars to a String---
                String readString =
                        String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
        return str;
    }

    public void setText(String str) {
        resultText.setText(str);
    }

    public String getURLAddress() {
        if (urlText != null) {
            return urlText.getText().toString();
        }
        return "empty";
    }

    public void setURLAddress(String str) {
        if (urlText != null) {
            urlText.setText(str);
        }
    }

    private InputStream OpenHttpConnection(String urlString)
            throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection)) {
            throw new IOException("Not an HTTP connection");
        }

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            Message lmsg;
            lmsg = new Message();
            lmsg.obj = "OpenHttpConnection";
            lmsg.what = 2;


            MainActivity.this.mHandler.sendMessage(lmsg);

            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }
}
